package com.cloud.open.support;

import com.cloud.common.bean.SessionInfo;
import com.cloud.common.context.SessionContext;
import com.cloud.common.support.SessionCache;
import com.cloud.open.config.AppConfig;
import com.cloud.open.entity.App;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.Set;

@Component
public class SessionHelper {
    private static final String APP_NAME = "Open";

    @Autowired
    private SessionCache sessionCache;

    @Autowired
    private AppConfig appConfig;

    public String createSession(App app, Set<String> authResources, Set<String> whitelistIps) {
        SessionInfo sessionInfo = new SessionInfo();
        sessionInfo.setAppName(APP_NAME);
        sessionInfo.setUserId(app.getId());
        sessionInfo.setSecret(app.getAppSecret());
        sessionInfo.setWhitelistIps(whitelistIps);
        sessionInfo.setAuthResources(authResources);
        return sessionCache.save(sessionInfo, appConfig.getSessionValidSeconds());
    }

    public void remove(Integer appId) {
        sessionCache.remove(APP_NAME, appId.toString());
    }

    public void logout() {
        sessionCache.remove(APP_NAME, SessionContext.getUserId().toString());
    }

    public void refreshWhitelistIps(Integer appId, Set<String> whitelistIps) {
        SessionInfo sessionInfo = sessionCache.get(APP_NAME, appId.toString());
        if (sessionInfo != null) {
            sessionInfo.setWhitelistIps(whitelistIps);
            sessionCache.save(sessionInfo, appConfig.getSessionValidSeconds());
        }
    }

    public void refreshAuthResources(Integer appId, Set<String> authResources) {
        SessionInfo sessionInfo = sessionCache.get(APP_NAME, appId.toString());
        if (sessionInfo != null) {
            sessionInfo.setAuthResources(authResources);
            sessionCache.save(sessionInfo, appConfig.getSessionValidSeconds());
        }
    }
}
